import React, { useState } from 'react';
import { 
  Upload, 
  message, 
  Button, 
  Card, 
  List, 
  Typography 
} from 'antd';
import { 
  UploadOutlined, 
  FileOutlined, 
  DeleteOutlined 
} from '@ant-design/icons';

const { Text } = Typography;

interface FileItem {
  uid: string;
  name: string;
  size: number;
  type: string;
}

const UploadPage: React.FC = () => {
  const [fileList, setFileList] = useState<FileItem[]>([]);

  const handleUpload = (info) => {
    const { status, originFileObj } = info.file;
    
    if (status === 'done') {
      const newFile: FileItem = {
        uid: originFileObj.uid,
        name: originFileObj.name,
        size: originFileObj.size,
        type: originFileObj.type
      };
      
      setFileList(prev => [...prev, newFile]);
      message.success(`${originFileObj.name} 上传成功`);
    } else if (status === 'error') {
      message.error(`${originFileObj.name} 上传失败`);
    }
  };

  const handleDelete = (uid: string) => {
    setFileList(prev => prev.filter(file => file.uid !== uid));
  };

  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
  };

  return (
    <Card title="文件上传">
      <Upload
        multiple
        beforeUpload={() => true}
        onChange={handleUpload}
        showUploadList={false}
      >
        <Button icon={<UploadOutlined />}>选择文件</Button>
      </Upload>

      <List
        style={{ marginTop: 16 }}
        bordered
        dataSource={fileList}
        renderItem={(file) => (
          <List.Item
            actions={[
              <DeleteOutlined 
                key="delete" 
                onClick={() => handleDelete(file.uid)}
                style={{ color: 'red', cursor: 'pointer' }}
              />
            ]}
          >
            <List.Item.Meta
              avatar={<FileOutlined />}
              title={file.name}
              description={
                <Text type="secondary">
                  {formatFileSize(file.size)} | {file.type}
                </Text>
              }
            />
          </List.Item>
        )}
      />
    </Card>
  );
};

export default UploadPage; 